package com.xiaoyu.lanling.feature.feedback

import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.net.Uri
import androidx.fragment.app.FragmentActivity
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.ListUtil
import com.xiaoyu.base.utils.RxUtils
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.feedback.*
import com.xiaoyu.lanling.event.media.mediaselector.MediaSelectorResultEvent
import com.xiaoyu.lanling.feature.feedback.data.FeedbackData
import com.xiaoyu.lanling.feature.feedback.datamodels.FeedbackMediaItemBase
import com.xiaoyu.lanling.media.selector.MediaSelector
import com.xiaoyu.lanling.media.selector.MediaSelectorFromType
import com.xiaoyu.lanling.media.selector.MediaSelectorType.IMAGE
import com.xiaoyu.lanling.router.Router
import com.xiaoyu.lanling.util.ImageFileCompressUtils
import com.xiaoyu.lanling.view.listener.BaseTextWatcher
import kotlinx.android.synthetic.main.activity_feedback.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

class FeedbackController(private val mActivity: FragmentActivity) {

    private var mProgressDialog: ProgressDialog? = null

    private var mAdapter: CubeRecyclerViewSimpleAdapter<FeedbackMediaItemBase>? = null
    private var editTextWatcher = EditTextWatcher()

    private val requestTag = Any()
    private var mFeedbackData: FeedbackData? = null
    private var isSubmitting: Boolean = false
    private var mType: String? = null

    init {
        initView()
        initAdapter()
        initBind()
        initEvent()
        initData()
    }

    fun onDestroy() {
        mActivity.feedbackEdit.removeTextChangedListener(editTextWatcher)
    }

    private fun initBind() {
        mActivity.submitButton.setOnClickDebounceListener {
            val content: String = mActivity.feedbackEdit.text.toString()
            if (isSubmitting || content.trim().isEmpty()) {
                return@setOnClickDebounceListener
            }
            isSubmitting = true
            mProgressDialog?.show()
            mFeedbackData?.submit(content)
        }
        mActivity.feedbackEdit.addTextChangedListener(editTextWatcher)
    }

    private fun initView() {
        mActivity.title = mActivity.getString(R.string.feedback_title)
        mActivity.textCountDesc.text = mActivity.getString(R.string.feedback_text_count_desc, 0.toString())

        mProgressDialog = ProgressDialog(mActivity)
        mProgressDialog?.setMessage(AppContext.getString(R.string.common_loading_please_wait))
        mProgressDialog?.setCancelable(false)
    }

    private fun initAdapter() {
        mAdapter = CubeRecyclerViewSimpleAdapter()
        FeedbackViewHolderManager.bindViewHolderForPublish(mAdapter)
        mActivity.feedbackImageRecyclerview?.adapter = mAdapter
    }

    private fun initData() {
        mType = mActivity.intent.getStringExtra(Constant.PARAM_TYPE)

        mFeedbackData = FeedbackData(requestTag, mType)
        mFeedbackData?.loadData()
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(mActivity, object : SimpleEventHandler() {

            @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
            fun onEvent(event: FeedbackPreviewListEvent) {
                mAdapter?.list = event.list
                mAdapter?.notifyDataSetChanged()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: FeedbackPublishAddMediaEvent) {
                openGallery()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: FeedbackEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                mProgressDialog?.dismiss()
                GlobalUI.getInstance().showToast(mActivity.getString(R.string.feedback_finished))
                mActivity.finish()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: FeedbackPublishPreviewPictureClickEvent) {
                if (event.item.position < 0) {
                    return
                }
                val pictureList: ArrayList<String> = ArrayList(mFeedbackData?.pictureBrowseList
                        ?: emptyList())
                if (pictureList.isNotEmpty()) {
                    Router.instance.gotoPhotoActivity(mActivity, event.item.path, pictureList)
                }
            }

            @Subscribe
            fun onEvent(event: FeedbackDeletePictureEvent) {
                mFeedbackData?.removePicture(Uri.parse(event.url))
            }

            @SuppressLint("CheckResult")
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: MediaSelectorResultEvent) {
                if (event.fromType != MediaSelectorFromType.FEEDBACK) {
                    return
                }

                if (event.mediaPathList.isEmpty()) {
                    return
                }

                if (event.type == IMAGE) {
                    ImageFileCompressUtils.compressBatchAsFile(event.imagePathList)
                            .compose(RxUtils.ioToMainSingleScheduler())
                            .filter { paths -> paths.isNotEmpty() }
                            .subscribe({ paths ->
                                val pictureUris = ListUtil.convertToList(paths.asList()) { it -> Uri.fromFile(File(it)) }
                                mFeedbackData?.addPicture(pictureUris)
                            }, { it.printStackTrace() })
                }
            }
        })
    }

    private fun openGallery() {
        if (mFeedbackData == null) {
            return
        }

        MediaSelector.instance.selectorForImage(mFeedbackData?.imageAddAbleCount
                ?: 1, true, MediaSelectorFromType.FEEDBACK)
    }

    private inner class EditTextWatcher : BaseTextWatcher() {
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            s?.let {
                mActivity.textCountDesc.text = mActivity.getString(R.string.feedback_text_count_desc, it.length.toString())
                mActivity.submitButton.isEnabled = it.isNotEmpty()
            }
        }
    }
}
